package com.zjy.heath_ms.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zjy.heath_ms.entity.Result;
import com.zjy.heath_ms.pojo.User;
import com.zjy.heath_ms.service.UserService;
import com.zjy.heath_ms.utils.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Objects;

/**
 * 项目名 heath_ms
 * 类名  UserController
 * 作者 lzq
 * 创建时间  2025/5/10 11:09
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Result login(@RequestBody User user){
        user = userService.login(user.getUsername(), user.getPassword());
        if (!Objects.isNull(user)) {
            String token = JWTUtil.generateJWT(user);
            return  Result.buildSuccess(token);
        }
        return Result.buildFail();
    }

    @GetMapping("/info")
    public Result info(HttpServletRequest request) {
        Integer userId = (Integer) request.getAttribute("userId");
        User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getId, userId));
        return Result.buildSuccess(user);
    }

    @PutMapping("/password")
    public Result editPassword(HttpServletRequest request, @RequestBody Map<String, Object> params) {
        boolean flag = userService.editPasswordByUserId(Integer.valueOf(request.getAttribute("userId").toString()),
                params.get("password").toString());
        return flag ? Result.buildSuccess() : Result.buildFail();

    }
}
